import { Pipe, PipeTransform } from '@angular/core';

const UNITS = [
  "", "十", "百", "千", "万", "十万", "百万", "千万", "亿", "十亿", "百亿", "千亿", "万亿"
]

@Pipe({
  name: 'optimizeUnit'
})
export class OptimizeUnitPipe implements PipeTransform {
  /**
   * 
   * 
   * @param {number} amount 原始数值
   * @param {number} [miniUnit=10000] 最小间隔单位
   * @param {number} [start=0] 起跳位置，0表示个，1表示十，以此类推
   * @param {number} [toFixed=2] 结果保留几位小数
   * @returns
   * 
   * @memberOf OptimizeUnitPipe
   */
  transform(amount: number, miniUnit: number = 10000, start: number = 0, toFixed = 2) {
    if (amount === undefined || amount === null || amount.toString() === "") return amount;
    return Math.abs(amount) >= miniUnit ?
      this.transform(amount / miniUnit, miniUnit, start + Math.log10(miniUnit), toFixed) :
      !isNaN(parseFloat(amount.toString())) ?
        parseFloat(amount.toString()).toFixed(toFixed) + UNITS[start] : amount + UNITS[start];
  }
} 